//
//  LGTPostDetailVC.swift
//  KJLGT
//
//  Created by jenkin on 2019/8/27.
//  Copyright © 2019年 jenkin. All rights reserved.
//

import UIKit
import SwiftyJSON
import WisdomHUD

class LGTPostDetailVC: LGTBaseVC, UITableViewDelegate, UITableViewDataSource{
    
    var stepCellClickBlock:ClickStepPathBlock?
    var topParam:Dictionary<String, Any>?
    var userModel:UserModel? = UserModel.share
    var moreView:UIView?
    var footMoreView:UIView?
    //任务请求参数
    var taskModel:TaskModel?
    //参数保存
    var submitDataInfo2:Dictionary<String, Any?> = [:]
    var tableView:UITableView?
    var isPreview:Bool = true  //默认是预览的
    var data:Array<Array<Dictionary<String, Any?>>> = Array.init()
    var infoData:Dictionary<String, Any> = [:]
    var clickBlock:ClickIndexBlock?
    //操作记录
    var timeStepArray:Array<Dictionary<String, Any>>?
    var footerView:UIView?
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setBlock()
        self.getData()
        NotificationCenter.default.addObserver(self, selector: #selector(paySuccessAction), name: Pay_Success_Note, object: nil)
    }

    @objc func paySuccessAction(){
        self.getData()
    }

    deinit {
        NotificationCenter.default.removeObserver(self, name: Pay_Success_Note, object: nil)
    }
    
    func setBlock(){
        weak var weakSelf = self
        self.reloadBlock = { () in
            weakSelf?.getData()
        }
        
        self.clickBlock = {(index:Int) in
            let vc:LGTRWZOperateRecodeVC = LGTRWZOperateRecodeVC()
            vc.data = weakSelf?.timeStepArray ?? []
            weakSelf?.navigationController?.pushViewController(vc, animated: true)
        }
        
        //步骤上的cell 点击
        self.stepCellClickBlock = {(data:Dictionary<String, Any>, path:IndexPath,  index:Int) -> Void in
            let row:Int = path.row - 1
            var reloadState:Bool = true
            switch index {
                
            case StepCellClickType.openurl.rawValue: //打开链接
                let url:String = data["subText"] as? String ?? ""
                let gotoURL:URL? = URL.init(string: url)
                if gotoURL != nil{
                    UIApplication.shared.open(gotoURL!, options: [:], completionHandler: nil)
                }
                reloadState = false
                break
                
            case StepCellClickType.copyurl.rawValue: //复制链接
                let url:String = data["subText"] as? String ?? ""
                UIPasteboard.general.string = url
                WisdomHUD.showSuccess(text: "复制成功")
                reloadState = false
                break
                
            default:
                break
            }
        }
    }
    
    override func setUI() {
        super.setUI()
        self.setBavBarStyle(navBarHiden: false, title: "任务详情", back: true)
        self.tableView = UITableView.init(frame: CGRect.init(x: 0.0, y: NavBarH, width: Double(KScreenW), height: Double(KScreenH) - NavBarH - TabBarH), style: UITableView.Style.plain)
        self.view.addSubview(self.tableView!)
        self.tableView?.backgroundColor = ViewBackColor
        self.tableView?.separatorStyle = UITableViewCell.SeparatorStyle.none
        self.tableView?.delegate = self as UITableViewDelegate
        self.tableView?.dataSource = self as UITableViewDataSource
        self.tableView?.register(LGTRWZPostDetailUrlStepCell.classForCoder(), forCellReuseIdentifier: "urlCell")
        self.tableView?.register(LGTRWZPostDetailCopyStepCell.classForCoder(), forCellReuseIdentifier: "copyCell")
        self.tableView?.register(LGTRWZPostDetailImageTextStepCell.classForCoder(), forCellReuseIdentifier: "imagetextcell")
        self.tableView?.register(LGTStepTitleViewCell.classForCoder(), forCellReuseIdentifier: "stepHeadCell")
        self.tableView?.register(LGTPostDetailTitleViewCell.classForCoder(), forCellReuseIdentifier: "titleCell")
        self.tableView?.register(LGTPostDetailTaskInfoViewCell.classForCoder(), forCellReuseIdentifier: "taskInfoCell")
        self.tableView?.register(LGTPostDetailRequestViewCell.classForCoder(), forCellReuseIdentifier: "requestCel")
        self.tableView?.register(LGTRWZPostTopViewCell.classForCoder(), forCellReuseIdentifier: "topCell")
//        tableView?.contentInset =
//            UIEdgeInsets.init(top: 0.0, left: 0.0, bottom: TabBarH, right: 0.0)
        self.tableView?.estimatedRowHeight = 40
        self.tableView?.rowHeight = UITableView.automaticDimension
        
        let moreBtn:UIButton = LGTViewCreateUtil.share.createTextLGTButton(title: "", font: Font_Bold_18, color: UIColor.clear, selectedColor: UIColor.clear, dW: SizeFitFloat(10), dH: SizeFitFloat(10))
        moreBtn.setImage(UIImage.init(named: "more_icon_pic"), for: UIControl.State.normal)
        moreBtn.setImage(UIImage.init(named: "more_icon_pic"), for: UIControl.State.selected)
        self.navBar.addSubview(moreBtn)
        moreBtn.snp.makeConstraints { (make) in
            make.right.equalTo(-SizeFitFloat(12))
            make.width.equalTo(SizeFitFloat(22))
            make.height.equalTo(SizeFitFloat(4))
            make.bottom.equalTo(-SizeFitFloat(19))
        }
        moreBtn.addTarget(self, action: #selector(moreAction), for: UIControl.Event.touchUpInside)
        tableView?.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: -SizeFitFloat(8), right: 0)
        self.view.backgroundColor = ViewBackColor
        self.footerView = UIView.init()
        self.footerView?.isHidden = true
        self.footerView?.backgroundColor = UIColor.white
        self.view.addSubview(self.footerView!)
        self.footerView!.snp.makeConstraints { (make) in
            make.bottom.left.equalTo(0)
            make.height.equalTo(TabBarH)
            make.width.equalTo(self.view)
        }
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.data.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let array = self.data[section]
        return array.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let array:Array<Dictionary<String, Any>> = self.data[indexPath.section]
        let info = array[indexPath.row]
        let collection:Bool = info["collection"] as? Bool ?? false
        let isurl:Bool = info["isurl"] as? Bool ?? false
        let imageAndText:Bool = info["imageAndText"] as? Bool ?? false
        let stepHead:Bool = info["stepHead"] as? Bool ?? false
        let isUserInfo:Bool = info["isUserInfo"] as? Bool ?? false
        let isRequest:Bool = info["isRequest"] as? Bool ?? false
        let isTaskInfo:Bool = info["isTaskInfo"] as? Bool ?? false
        let isTop:Bool = info["isTop"] as? Bool ?? false
        
        if isTop == true{
            let cell:LGTRWZPostTopViewCell = tableView.dequeueReusableCell(withIdentifier: "topCell", for: indexPath) as! LGTRWZPostTopViewCell
            cell.model = info
            cell.clickBlock = self.clickBlock
            return cell
        }
        if isUserInfo == true{
            let cell:LGTPostDetailTitleViewCell = tableView.dequeueReusableCell(withIdentifier: "titleCell", for: indexPath) as! LGTPostDetailTitleViewCell
             cell.model = info
            return cell
        }else if isRequest == true{
            let cell:LGTPostDetailRequestViewCell = tableView.dequeueReusableCell(withIdentifier: "requestCel", for: indexPath) as! LGTPostDetailRequestViewCell
             cell.model = info
            return cell
        }else if isTaskInfo == true{
            let cell:LGTPostDetailTaskInfoViewCell = tableView.dequeueReusableCell(withIdentifier: "taskInfoCell", for: indexPath) as! LGTPostDetailTaskInfoViewCell
             cell.model = info
            return cell
        }
        //复制 和 收集
        else if collection == true{
            let cell:LGTRWZPostDetailCopyStepCell = tableView.dequeueReusableCell(withIdentifier: "copyCell", for: indexPath) as! LGTRWZPostDetailCopyStepCell
            cell.path = indexPath
            cell.model = info
            return cell
        }
            //打开url
        else if isurl == true{
            let cell:LGTRWZPostDetailUrlStepCell = tableView.dequeueReusableCell(withIdentifier: "urlCell", for: indexPath) as! LGTRWZPostDetailUrlStepCell
            cell.path = indexPath
            cell.model = info
            cell.stepCellClickBlock = self.stepCellClickBlock
            return cell
        }
            //图片
        else if imageAndText == true{
            let cell:LGTRWZPostDetailImageTextStepCell = tableView.dequeueReusableCell(withIdentifier: "imagetextcell", for: indexPath) as! LGTRWZPostDetailImageTextStepCell
            cell.path = indexPath
            cell.model = info
            return cell
        }
            //操作步骤头部
        else if stepHead == true{
            let cell:LGTStepTitleViewCell = tableView.dequeueReusableCell(withIdentifier: "stepHeadCell", for: indexPath) as! LGTStepTitleViewCell
            return cell
        }
        else{
            let cell:LGTRWZPostSelectCell = tableView.dequeueReusableCell(withIdentifier: "selectCell", for: indexPath) as! LGTRWZPostSelectCell
            cell.model = info
            return cell
        }
    }
    
    //获取数据
    func getData(){
        
        //预览
        if self.isPreview == true{
            self.initData()
            return
        }
        
        if self.taskModel == nil{
            return
        }
        
        let id:Int = self.taskModel!.id ?? 0
        let param = ["id":id]
        
        //获取订单详情
        weak var weakSelf = self
        LGTHttpUtil.httpUtil.requestData(url: Task_Detail_URL, param: param, success: { (json) in
            //数据转换
            weakSelf?.dataChange(json: json)
        }) { (json) in
             weakSelf?.showNoData(image: Net_NoData_Image, text: Net_Error_Text, subText: Net_Reload_Text)
        }
    }
    
    //数据转换
    func dataChange(json:Dictionary<String, Any>){
        self.taskInfoChangeSubmitInfo(json: json)
        //数据初始化
        self.initData()
    }
    
//  more 更多
//  stop 暂停
//  withdraw 撤回
//  append 追加
//  go_on 继续
//  modify 修改
//  applicationforissuance 以此为模版继续发布
//  applicationforissuance 申请发布

//底部视图
// 3 派发中： 更多 暂停 修改
// 4 暂停中： 撤回 继续 查看单价
// 5 已撤回 申请发布
// 预览 修改 和 申请发布
// 2 未通过  无按钮
// 1 审核中  无按钮
// 7 已完成  查看单价  以此为模版继续发布
// 6 已过期 查看单价 以此为模版继续发布
// 8 已下架 查看单价 以此为模版继续发布
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view:UIView = UIView.init()
        view.backgroundColor = ViewBackColor
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == self.data.count - 1{
            return SizeFitFloat(1)
        }
        return SizeFitFloat(8)
    }
    
    @objc func moreAction(){
        
        if self.moreView == nil{
            self.moreView = UIView.init()
            self.moreView?.backgroundColor = UIColor.white
            self.moreView?.layer.borderColor = GrayColor.cgColor
            self.moreView?.layer.borderWidth = 1
            self.view.addSubview(self.moreView!)
            self.moreView?.isHidden = true
            self.moreView?.snp.makeConstraints({ (make) in
                make.width.equalTo(SizeFitFloat(100))
                make.height.equalTo(SizeFitFloat(81))
                make.top.equalTo(NavBarH)
                make.right.equalTo(-SizeFitFloat(9))
            })
            
            let  gerOrderDescBtn:LGTButton = LGTViewCreateUtil.share.createTextLGTButton(title: "接单声明", font: Font_Normal_18, color: TextColor, selectedColor: TextColor, dH: SizeFitFloat(5))
            self.moreView?.addSubview(gerOrderDescBtn)
            gerOrderDescBtn.snp.makeConstraints { (make) in
                make.left.right.equalTo(0)
                make.top.equalTo(SizeFitFloat(12))
                make.height.equalTo(SizeFitFloat(20))
            }
            
            let  freeDesc:LGTButton = LGTViewCreateUtil.share.createTextLGTButton(title: "免责声明", font: Font_Normal_18, color: TextColor, selectedColor: TextColor, dH: SizeFitFloat(5))
            self.moreView?.addSubview(freeDesc)
            freeDesc.snp.makeConstraints { (make) in
                make.left.right.equalTo(0)
                make.top.equalTo(SizeFitFloat(48))
                make.height.equalTo(SizeFitFloat(20))
            }
        }
        
        self.moreView?.isHidden = !self.moreView!.isHidden
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        self.moreView?.isHidden = true
        self.footMoreView?.isHidden = true 
    }
}
